<template>
	<div class="pageMiddle">
		<div class="main-title">
			SHS-IM
		</div>
		<div class="mainBox">
			<div class="relationship ">
				<div class=" ">
					<div :class="{relationshipItem:true,isActive:value.isActive}"
						v-for="value,index in relationshipList" :key="`${value.isGroup}${value.Id}`"
						@click="handleActive(value.otherId,index)">
						<div class="photo">
							<div class="TipREDBox">
								<div :class="{TipRED:value.isNewMsgTipRed}"></div>
							</div>
							<el-image class="width50  height50 borderr50 marginR5"
								:src="value.otherUrl+'?w=50&h=50&q=75'" fit="fill">
								<div slot="error" class="image-slot">
									<el-image class="width50  height50 borderr50 marginR5"
										:src="$handledImageError(value.otherUrl+'?w=50&h=50&q=75',1)" fit="fill">
										<div slot="error" class="image-slot">
											<i class="el-icon-picture-outline" style="font-size: 50px;"></i>
										</div>
									</el-image>
								</div>
							</el-image>
						</div>
						<div class="">
							<div class="relationshipItemND">
								<div class="relationshipItemName overflow">
									{{value.otherName}}
								</div>

								<div class="relationshipItemlasetDate">
									{{ formatDate(value.lastTime,10)}}
								</div>
							</div>
							<div class="relationshipItemMsg overflow">
								<span v-show="value.tempMessage"><span
										class="color-error font12">[草稿]</span>{{value.tempMessage}}</span>
								<span v-show="!value.tempMessage"
									v-if='value.isGroup===1 '>{{value.lastMessage || "快来发送第一条消息吧"}}</span>
								<span v-show="!value.tempMessage" v-else>{{value.lastMessage || "跟好友打个招呼吧~"}}</span>
							</div>

						</div>
					</div>
				</div>
			</div>
			<div class="content ">
				<div class="contentTop  userSelectNone shs-flex"
					style="align-items: center;justify-content:space-between;padding-right: 20px;">
					<div class="contentTitle overflow">
						{{activeItem.otherName}}<span style="color: #ccc;">
							[{{activeItem.isGroup===1?"群":""}}Id号:{{activeItem.activeId}}]</span>
					</div>
					<div class="ControlsBox font24" @click="openGroupDialog">
						...
					</div>
				</div>
				<el-dialog :modal="false" :title="activeItem.otherName" :visible.sync="GroupDialogIsShow" width="45%"
					center :destroyOnClose='true' @closed="handleClosed" class="ControlsBoxDialog">
					<el-form ref="GroupDialogForm" :model="relationshipListTemp" :rules="relationshipListTempRules"
						label-width="100px" size="mini">
						<el-form-item label="">
							<div v-if="!relationshipListTemp.isneed" class="GroupDialogFormUserListBox">
								<div class="" v-for="item,index in relationshipListTemp.groupUserList">
									<div class="item">
										<el-image alt="user avatar"
											:src="$handledImageError(item.url+'?w=50&h=50&q=75',1)"
											class="width50 height50 borderr50">
										</el-image>
										<div>{{item.username}}</div>
									</div>
								</div>
							</div>
							<div class="color-smill" v-else>
								所有用户可见
							</div>
						</el-form-item>
						<el-form-item label="群聊ID:">
							<span>{{relationshipListTemp.otherId}}</span>
						</el-form-item>
						<el-form-item label="群聊名称:" prop="otherName" >
							<el-input v-model="relationshipListTemp.otherName" :placeholder="activeItem.otherName"
								v-if="relationshipListTemp.isGroupAdmin || userIsAdmin==1"
								@blur="handledUpdate('groupName')"></el-input>
							<span v-else>{{relationshipListTemp.otherName}}</span>
						</el-form-item>
						<el-form-item label="群聊头像:">
							<el-image alt="avatar"
								:src="$handledImageError(relationshipListTemp.otherUrl+'?w=50&h=50&q=75',1)"
								class="width50 height50 borderr50"> </el-image>
							<div class="shs-flex-center-start "
								v-if="relationshipListTemp.isGroupAdmin || userIsAdmin==1">
								<el-image alt="avatar" :src="relationshipListTemp.newOtherUrl"
									v-show="relationshipListTemp.newOtherUrl" class="width50 height50 borderr50">
								</el-image>
								<el-button type="success" icon="el-icon-check" circle @click="handledUpdate('groupUrl')"
									v-show="relationshipListTemp.newOtherUrl" style="margin-left: 5px;"></el-button>
								<single-upload tipText="换新头像" class="marginL5 marginT5" :showTip='false'
									v-model="relationshipListTemp.newOtherUrl" :isshowFileList='false'></single-upload>
							</div>
						</el-form-item>
						<!-- <el-form-item label="群聊成员(后期删除这个字段):" label-width="200px">
							{{relationshipListTemp.userlist}}
						</el-form-item> -->
						<el-form-item v-if="relationshipListTemp.isneed!=1">
							<el-button @click="handledExit('group')" type="danger">退出群聊</el-button>
						</el-form-item>
						<el-form-item v-else label="备注:">
							<span class="color-smill font12">官方群聊</span>
						</el-form-item>
					</el-form>

				</el-dialog>
				<el-dialog :modal="false" :title="activeItem.otherName" :visible.sync="userDialogIsShow" width="45%"
					center :destroyOnClose='true' @closed="handleClosed" class="ControlsBoxDialog">
					<el-form ref="userDialogForm"  label-width="80px" size="mini">
						<el-form-item label="">
							<div class="">
								<img alt="user avatar"
									:src="$handledImageError(relationshipListTemp.otherUrl+'?w=50&h=50&q=75',1)"
									class="width50 height50 borderr50" />
								<div>{{relationshipListTemp.otherName}}</div>
							</div>
						</el-form-item>
						<el-form-item label="用户ID:">
							<span>{{relationshipListTemp.otherId}}</span>
						</el-form-item>
						<el-form-item label="用户名称:">
							<el-input v-model="relationshipListTemp.otherName"
								v-if="relationshipListTemp.isGroupAdmin"></el-input>
							<span v-else>{{relationshipListTemp.otherName}}</span>
						</el-form-item>
						<el-form-item label="添加时间:">
							<span>{{handledFormatDateHMS(relationshipListTemp.createTime)}}</span>
						</el-form-item>
						<el-form-item>
							<el-button @click="handledExit('user')" type="danger">删除好友</el-button>
						</el-form-item>
					</el-form>

				</el-dialog>
				
				<div class="contentMiddle scrollbarOverflow  userSelectNone" ref="scrollBoxRef"
					@scroll="handleWatchScroll">
					<div class=" textCenter color-smill" v-show="msgConfig.msglistResults" @click="handleChandeMsg">
						查看更多消息</div>
					<div class="contentBox" v-for="key,index in messageList" :key="key.messageId">
						<div class="contentBoxLeft" v-if="key.fromId!=activeItem.fromId">
							<div class="fromPhoto" @click="handleOpenDetails(key.fromId)">
								<el-image class="imageCls borderr50" :src="key.fromUrl+'?w=50&h=50&q=75'" fit="fill">
									<div slot="error" class="image-slot">
										<el-image class="imageCls borderr50"
											:src="$handledImageError(key.fromUrl+'?w=50&h=50&q=75','tx')" fit="fill">
										</el-image>
									</div>
								</el-image>
							</div>
							<div class="contentName" v-if="isShowName">
								{{key.userName || key.fromName}}
							</div>
							<div class="contentMessageDateBox">
								<div class="contentMessageDate">
									{{ formatDate(key.createTime)}}
								</div>
							</div>

							<div class="fromMessage">
								<div v-if="key.type===1">
									<leng-message :message='key.message' :maslength="key.msglength"></leng-message>
								</div>
								<div v-else-if="key.type===11">
									<el-image lazy class="msgImagesCls " :src="key.imagesUrl+'?w=300&h=250&q=30'"
										fit="fill" @error.once="handledImagesErrorOne(key.imagesUrl,index)"
										:preview-src-list="messagePreviewList"
										:initialIndex="originalPreviewList.indexOf(key.imagesUrl)">
									</el-image>
								</div>
							</div>


						</div>
						<div class="contentBoxRight" v-else>
							<div class="fromPhoto">
								<el-image class="imageCls borderr50" :src="key.fromUrl+'?w=50&h=50&q=75'" fit="fill"
									:preview-src-list="[key.fromUrl]">
									<div slot="error" class="image-slot">
										<el-image class="imageCls borderr50"
											:src="$handledImageError(key.fromUrl+'?w=50&h=50&q=75','tx')" fit="fill"
											:preview-src-list="[$handledImageError(key.fromUrl,'tx')]">
										</el-image>
									</div>
								</el-image>
							</div>
							<div class=" contentNameRight" v-if="isShowName">
								{{key.userName || key.fromName}}
							</div>
							<div class="contentMessageDateBox">
								<div class="contentMessageDate">
									{{ formatDate(key.createTime)}}
								</div>
							</div>
							<div class="fromMessage">
								<div v-if="key.type===1">
									<leng-message :message='key.message' :maslength="key.msglength"></leng-message>
								</div>
								<div v-else-if="key.type===11">
									<el-image lazy class="msgImagesCls" :src="key.imagesUrl+'?w=300&h=250&q=30'"
										fit="fill" @error.once="handledImagesErrorOne(key.imagesUrl,index)"
										:preview-src-list="messagePreviewList"
										:initialIndex="originalPreviewList.indexOf(key.imagesUrl)">
									</el-image>
								</div>
							</div>


						</div>
					</div>
				</div>


				<div class="MsgTipBox" v-show="isShowNewmobileTip">
					<div class="MsgTip" @click="handlerShowTip">
						<i class="iconfont icon-shuangxiangxiajiantou"></i><span></span>
					</div>
				</div>
				<div class="MsgTipBox" v-show="isShowNewMsgTip">
					<div class="MsgTip" @click="handlerShowTip">
						<i class="iconfont icon-shuangxiangxiajiantou"></i><span>有新消息</span>
					</div>
				</div>
				<div class="contentDown">
					<el-input type="textarea" :autosize="{ minRows: 4, maxRows:4}" resize='none'
						@keydown.enter.native="handleEnterKey" :maxlength='contentMaxlength'
						@blur="handledMessage(activeItem.message)" :placeholder="MsgPlaceholder"
						v-model="activeItem.message">
					</el-input>
				</div>
				<div class="hintContentButtom">
					<div style="display: inline-block;margin-left:0.6rem;cursor: pointer;">
						<i @click="dialogVisibleSendImage=true" class="iconfont icon-tupian"></i>
						<div class="updateImage">
							<el-dialog :title="`发送至:${activeItem.otherName}`" :visible.sync="dialogVisibleSendImage"
								@close="handleCloseSendImage">
								<single-upload v-model="activeItem.imagesUrl" :maxSendSize="30"
									:isdrag="true"></single-upload>
								<el-button :disabled='activeItem.imagesUrl==""' style="margin-top: 20px;"
									@click="handleSendImage">发送</el-button>
							</el-dialog>
						</div>
					</div>
					<div style="display: inline-block;margin-left:0.6rem;position: relative;" ref="RefEmojiElement">
						<i @click="VisibleEmojiElement=true" style="top: -2px;position: relative;"
							class="cursorPointer iconfont icon-biaoqingbao"></i>
						<emoji-Element style="width: 500px;position:absolute;margin: 0 auto;left:-40px;top: -510px;"
							:Visible="VisibleEmojiElement"
							@handledVisibleEmojiElementChildEmit='handledVisibleEmojiElementChildEmit'></emoji-Element>
					</div>
					<div class="hintContentLength">
						<i>使用Enter快速发送 </i>
						<i class="hintContentNowLength"
							v-show="activeItem.message.length>0">{{activeItem.message.length}}</i>
						<i class="" v-show="activeItem.message.length>12000"> / {{contentMaxlength}}</i>
					</div>
					<el-tooltip class="item" effect="dark" :hide-after='800' content="使用Ctrl+Enter快速发送"
						placement="bottom-start">
						<el-button class="contentDownSend" size='mini' type="primary"
							:disabled="activeItem.message.length==0" @click="handleSend">发送</el-button>
					</el-tooltip>
				</div>

				<relationship-add ref="relationshipAdd"></relationship-add>
				
			</div>
		</div>
	</div>
</template>

<script>
	import Storage from "@/utils/session.js"
	import singleUpload from "@/components/Upload/singleUpload"
	import EmojiElement from "@/components/EmojiElement/EmojiElement"
	import LengMessage from "@/components/LengMessage/LengMessage"

	import RelationshipAdd from "@/components/relationship/index"
	
	import {
		getRelationList,
		DeleteContact
	} from "@/api/relationshipUser"
	import {
		IMSend,
		IMGetMessage
	} from "@/api/message"
	import {
		getdate,
		DateIfSimilar,
		formatDateHMS,
		formatTime
	} from "@/utils/base"
	import {
		getGroupUserList,
		upGroupName,
		upGroupUrl,
		exitGroup
	} from "@/api/group"
	import {
		debounce
	} from "@/utils/common.js";
	export default {
		name: "pageMiddle",
		components: {
			singleUpload,
			EmojiElement,
			LengMessage,
			RelationshipAdd,
		},
		data() {
			let pageSizes = 20
			return {
				contentMaxlength: 15000, //聊天字数限制,
				isShowName: true, //是否显示聊天姓名
				isFirstLoad: true, //首次加载不执行
				//用户 接受方信息 
				activeItem: {
					type: 1, //信息业务1：文字  11：图片
					fromId: 0, //发送方id
					fromName: "", //发送方名称
					fromUrl: "", //发送方头像
					oldIndex: 0, //上一个
					activeId: 1, //激活id / 接收方id
					isGroup: 1, //是否是群组
					otherName: "社会数官方", //接收方名称
					message: "",
					imagesUrl: "", //图片地址
					isneed: 0, //是否是必须进的群
					msglength: 0, //信息字数
					isGroupAdmin: false, //是否是群聊管理员
				},
				//信息列表对象
				allMessageList: {},
				//显示的信息列表
				messageList: [],
				//联系人列表
				relationshipList: [],
				//临时联系人
				relationshipListTemp: {},
				relationshipListTempRules: {
					otherName: [{
						required: true,
						message: '请输入群聊名称',
						trigger: 'blur'
					}]
				},
				newArray: new Array(),
				pageConfig: {
					pageSizes: pageSizes, //信息条数
					pageNum: 1, //页数 第n页
				},
				onlineUsers: [], //在线列表
				clickActiveCount: 0, //激活点击问题
				isShowNewMsgTip: false, //本页 新消息 提示
				isShowNewmobileTip: false, //下滑操作
				difference: 0, // 计算滚动条差值
				dialogVisibleSendImage: false, //发送图片的dialog标识
				VisibleEmojiElement: false, //表情包的dialog标识
				GroupDialogIsShow: false, //群聊信息详情dialog标识
				userDialogIsShow: false, //普通用户信息详情dialog标识
				previewList: [], //聊天预览图列表
				originalPreviewList: [], //聊天预览图列表 原始数据
				msgConfig: {
					minScrollTop: 300, //距离msg顶部height 小于300就查询
					isExecuteShowMore: false, //距离msg顶部height
					msglistResults: false, //msg查询结果 false 终止查询
				},
				userIsAdmin: 0, //是否是管理员
			}
		},
		mounted() {
			//获取用户信息
			// this.handleResize();
			let _this = this
			this.$refs["scrollBoxRef"].addEventListener("scroll", function() {
				if (_this.$refs["scrollBoxRef"].scrollTop <= _this.msgConfig.minScrollTop) {
					if (_this.msgConfig.isExecuteShowMore && _this.msgConfig.msglistResults) {
						_this.handleChandeMsg();
					}
				}
			})

		},

		beforeDestroy() {
			// 在组件销毁前移除事件监听
			document.removeEventListener('click', this.handledVisibleEmojiElement);
		},
		computed: {
			MsgPlaceholder() {
				let msg = "善语结善缘,恶语伤人心"
				if (this.activeItem.otherName == '意见反馈') {
					msg = "没有谁的意见微不足道 是你的声音让这个世界变更好"
				} else if (this.activeItem.otherName == '树洞') {
					msg = "校园树洞，你的心声我来听。"
				}
				return msg
			},
			storeUserinfo() {
				return this.$store.getters.userInfo;
			},
			isGetRelationshiplist() {
				return this.$store.getters.isGetRelationshiplist
			},
			newMessage() {
				return this.$store.getters.newMessage || ""
			},
			//信息页面预览图列表
			messagePreviewList() {
				return this.previewList
			},
			isExecute() {
				return this.$store.getters.isExecute
			},
		},
		methods: {
			/**定向刷新联系人列表*/
			handeledGroupInfomation(data) {
				try {
					for (let i = 0; i < this.relationshipList.length; i++) {
						if (this.relationshipList[i].otherId === data.Id && this.relationshipList[i].isGroup == 1) {
							this.relationshipList[i] = Object.assign({}, this.relationshipList[i], this.activeItem, data)
							if (this.activeItem.activeId == data.Id) {
								let temp = this.relationshipList[i]
								this.activeItem = Object.assign({}, this.relationshipList[i])
								this.relationshipListTemp = Object.assign({}, this.relationshipList[i])
								if (this.activeItem.isGroup == 1) {
									this.handledisGroupAdmin();
								}
							}
							break;
						}
					}
				} catch (error) {
					console.log("err", error.message);
				}

			},
			/**修改群聊信息*/
			handledUpdate(code) {
				if (code == 'groupName') {
					if (this.activeItem.otherName != this.relationshipListTemp.otherName && this.relationshipListTemp
						.otherName.trim().length != 0) {
						upGroupName({
							username: this.relationshipListTemp.otherName,
							Id: this.activeItem.activeId
						}).then(res => {
							this.$notify({
								title: '',
								message: '修改成功',
								type: 'success',
								duration: 800
							})
						})
					}
				} else if (code == 'groupUrl') {
					upGroupUrl({
						url: this.relationshipListTemp.newOtherUrl,
						Id: this.activeItem.activeId
					}).then(res => {
						this.$notify({
							title: '',
							message: '修改成功',
							type: 'success',
							duration: 800
						})
						//后端操作全部重新请求
						this.relationshipListTemp.newOtherUrl = ""
					})
				}
			},
			/**退出 删除操作*/
			handledExit(code) {
				if (code == 'group') {
					this.$confirm('确认退出该群, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						exitGroup({
							userId: this.activeItem.fromId,
							Id: this.relationshipListTemp.Id,
							userlist: this.relationshipListTemp.userlist
						}).then(res => {
							this.$notify({
								title: '系统消息',
								message: res.message,
								type: 'success',
								duration: 850
							});
							this.GroupDialogIsShow = false;
							this.handleGroupSet(1, 1)
						})
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消',
							duration: 850
						});
					});
				} else if (code == 'user') {
					this.$confirm('此操作将删除该好友， 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						DeleteContact({
							deleter: this.activeItem.fromId,
							deletedContact: this.relationshipListTemp.otherId
						}).then(res => {
							this.$notify({
								title: '系统消息',
								message: res.message,
								type: 'success',
								duration: 850
							});
							this.userDialogIsShow = false;
							this.handleGroupSet(1, 1)
						})

					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消',
							duration: 850
						});
					});

				}
			},
			//打开群聊详情信息弹窗
			openGroupDialog() {
				if (this.relationshipListTemp.isGroup==1) {
					this.GroupDialogIsShow = true;
				} else if(this.relationshipListTemp.isGroup==0){
					this.userDialogIsShow = true;
				}

			},
			handledisGroupAdmin() {
				try {
					if (this.relationshipListTemp.userlist && this.relationshipListTemp.isGroup) {
						this.activeItem.isGroupAdmin = this.relationshipListTemp.userlist.split(',')[0] == this.activeItem
							.fromId && this.relationshipListTemp.isneed == 0
						if (this.activeItem.isneed != 1) {
							this.handledGetGroupUserList(this.relationshipListTemp.userlist)
						}
					}
				} catch (error) {
					console.log("handledisGroupAdmin", error);
				}
			},
			handleClosed() {
				this.GroupDialogIsShow = false;
				this.userDialogIsShow = false;
			},
			//打开用户信息详情页
			handleOpenDetails(otherid) {
				this.$refs["relationshipAdd"].initData(true, otherid, this.$store.getters.userlist)
			},
			//第一层图片错误触发
			handledImagesErrorOne(url, index) {
				let newURL = this.$handledImageError(url, 'msg')
				this.messageList[index].imagesUrl = newURL;
				let plindex = this.previewList.indexOf(url)
				if (plindex != -1) {
					this.previewList[plindex] = newURL
				}
			},
			handleResize() {
				if (!window.matchMedia('(max-width:768px)').matches) {
					this.initInfomation();
				}
			},
			//初始化
			initInfomation() {
				let _this = this;
				let userinfo = _this.storeUserinfo.Id ? _this.storeUserinfo : JSON.parse(Storage.getSession())
				_this.activeItem.fromId = userinfo.Id;
				_this.activeItem.fromName = userinfo.username;
				_this.activeItem.fromUrl = userinfo.url;
				_this.userIsAdmin = userinfo.isAdmin;
				_this.activeItem.isGroupAdmin = false;

				//获取联系人列表
				_this.handlerGetRelatinshipList(_this.activeItem.fromId).then(res => {
					// _this.handleGroupSet(28, 0)//初始化聊天对象
					_this.handleGroupSet(this.relationshipList[0].otherId, this.relationshipList[0].isGroup)
				})

			},
			//emoji事件显隐处理 检查事件的目标是否在当前组件的DOM元素内
			handledVisibleEmojiElement(data) {
				if (!this.$refs["RefEmojiElement"].contains(event.target)) {
					this.VisibleEmojiElement = false;
				}
			},
			//emoji事件显隐处理
			handledVisibleEmojiElementChildEmit(obj) {
				this.VisibleEmojiElement = obj.VisibleEmojiElement;
				this.activeItem.message = this.activeItem.message + obj.value;
			},
			//按键 快捷键
			handleEnterKey(value) {
				let l1 = this.activeItem.message.length;
				let l2 = this.activeItem.message.trim().length
				if (l1 != 0 && l2 === 0) {
					this.activeItem.message = ""
				}
				if (l2 === 0) {
					return
				}
				if (!value.ctrlKey) {
					this.handleSend();
				} else {
					this.activeItem.message += '\n'
				}
			},
			//消息文本操作
			beforeHandleCommand(type, value) {
				return {
					type,
					value
				}
			},
			handleCommand(key) {
				if (key.type === 'copy') {
					let value = key.value.type === 1 ? key.value.message : key.value.imagesUrl
					this.$handledMsgCopy(value)
				}
			},
			/*获取联系人列表*/
			handlerGetRelatinshipList(id) {
				if (!id) {
					return Promise.reject(new Error('ID is required'));
				}
				this.clickActiveCount = 0;
				return getRelationList({
					fromId: id
				}).then(data => {
					let res = data.data;
					this.relationshipList = new Array();
					let userlist = []
					for (let i = 0; i < res.length; i++) {
						res[i].updateTime = getdate(res[i].updateTime)
						res[i].isActive = 0;

						if (this.activeItem.isGroup === res[i].isGroup && (this.activeItem.activeId === res[i]
								.Id || this.activeItem.activeId === res[i].otherId)) {
							res[i].isActive = 1;
							this.activeItem.otherName = res[i].otherName
						}
						if (i == res.length - 1) {
							this.$set(this.relationshipList, this.relationshipList.length, res[i]);
						} else {
							this.relationshipList.push(res[i]);
						}
						if (res[i].isGroup == 0) {
							userlist.push(res[i].otherId)
						}
					}
					this.$store.commit("setUserlist", userlist);
					return this.relationshipList;
				}).catch(error => {
					console.error('Failed to get relationship list:', error);
					throw [];
				});
			},
			/**
			 * 获取指定聊天信息列表 
			 * @param string otherId 查询的对方id
			 * @param boolean isupMsg 是否是查看更多消息
			 */
			handleGetMessageList(otherId, isupMsg = false) {
				this.msgConfig.isExecuteShowMore = false
				if (!isupMsg) {
					this.previewList = []
					this.originalPreviewList = []
				}

				if (!this.activeItem.fromId) {
					return
				}
				//获取本地缓存 查看总数再按照pagenum查询新的
				let obj = {
					fromId: this.activeItem.fromId,
					otherId: otherId,
					isGroup: this.activeItem.isGroup,
					pageSizes: this.pageConfig.pageSizes,
					pageNum: this.pageConfig.pageNum
				}
				IMGetMessage(obj).then(data => {
					let l = data.data.length;
					if (l > 0 && this.pageConfig.pageSizes < data.count) {
						this.msgConfig.msglistResults = true
					} else {
						this.msgConfig.msglistResults = false
					}

					if (data.count) {
						//时间处理
						if (!isupMsg) {
							this.messageList = this.handlerDate(data.data);
							this.handlerScrollDown("scrollBoxRef");
						} else {
							this.messageList = [...this.handlerDate(data.data), ...this.messageList]
						}
						this.msgConfig.isExecuteShowMore = true
					}
				})
			},

			// 时间处理 plist 预览图片处理
			handlerDate(arr, isupMsg = false) {
				let plist = []
				for (let i = 0; i < arr.length; i++) {
					arr[i].createTime = getdate(arr[i].createTime)
					if (arr[i].type == 11) {
						plist.push(arr[i].imagesUrl)
					}
				}
				if (!isupMsg) {
					this.previewList = this.originalPreviewList = plist;
				} else {
					this.previewList.unshift(plist)
					this.originalPreviewList.unshift(plist)
				}
				return arr;
			},
			//找到固定联系人或群 并设置为激活态
			handleGroupSet(activeId, groupType) {
				this.relationshipList.forEach((value, index, arr) => {
					if (value.otherId === activeId && value.isGroup === groupType) {
						this.clickActiveCount = 0;
						this.handleActive(value.otherId, index);
					}
				})
				//滑到底部
				this.handlerScrollDown("scrollBoxRef");
			},
			//清空激活态
			clearRelationActive() {
				this.relationshipList.forEach((value, index, arr) => {
					value.isActive = 0
				})
			},
			//获取群聊用户列表 信息
			handledGetGroupUserList(userlist) {
				getGroupUserList({
					userlist
				}).then(res => {
					this.$set(this.relationshipListTemp, "groupUserList", res.data)
				})
			},
			/**编辑信息失焦触发 */
			handledMessage(msg = "") {
				try {
					this.relationshipList.some((value, index) => {
						if (value.otherId === this.activeItem.activeId && value.isGroup === this.activeItem
							.isGroup) {
							this.$set(this.relationshipList[index], 'tempMessage', msg)
							return true; // 返回 true 来终止 some 循环
						}
						return false; // 继续循环
					});

				} catch (error) {
					console.log("编辑信息失焦触发--error", error.message);
				}
			},
			// 激活接受者Id
			handleActive: debounce(function(otherId, index) {
				if (this.clickActiveCount) {
					this.relationshipList[this.activeItem.oldIndex].isActive = 0;
				} else {
					this.clearRelationActive();
				}
				this.relationshipList[index].isActive = 1;
				this.relationshipList[index].isNewMsgTipRed = false; //消除提示的红点
				this.activeItem.isGroup = this.relationshipList[index].isGroup; //是否是群
				this.activeItem.otherName = this.relationshipList[index].otherName;
				this.activeItem.oldIndex = index; //把当前的索引赋值替换掉旧索引
				this.activeItem.activeId = otherId;
				this.activeItem.isneed = this.relationshipList[index].isneed;
				this.activeItem.message = this.relationshipList[index].tempMessage || ""; //临时编辑的消息
				this.clickActiveCount = 1;
				this.activeItem.isGroupAdmin = false;
				this.relationshipListTemp ={};
				this.relationshipListTemp = Object.assign({}, this.relationshipList[index])
				this.isShowNewMsgTip = false;
				//初始化
				this.pageConfig.pageSizes = 20;
				this.pageConfig.pageNum = 1;
				this.messageList = Array();
				// //判断是否是群聊管理员
				this.handledisGroupAdmin();
				// 获取数据库信息
				this.handleGetMessageList(otherId);
			}, 200),
			//设置信息列表
			handledChangeMessageList(data) {
				this.$set(this.messageList, this.messageList.length, data);
				if (data.type === 11) {
					this.previewList.push(data.imagesUrl)
					this.originalPreviewList.push(data.imagesUrl)
				}
			},
			//发送信息image
			handleSendImage: debounce(function() {
				this.activeItem.type = 11;
				if (this.activeItem.imagesUrl.trim().length === 0) {
					this.$notify({
						title: '',
						message: 'Error:need select image',
						type: 'info',
						duration: 800
					})
					return;
				}
				try {
					this.$store.commit("setOnSend", this.activeItem)
					this.dialogVisibleSendImage = false;
				} catch (e) {
					//TODO handle the exception
					this.$notify({
						title: '',
						message: 'Error:send images \n请检查网络设置',
						type: 'error',
						duration: 3000
					})
				}
			}),
			//发送信息image 关闭回调
			handleCloseSendImage() {
				this.activeItem.imagesUrl = ""
				this.activeItem.type = 1;
			},
			//发送信息
			handleSend: debounce(function() {
				this.activeItem.type = 1;
				let l = this.activeItem.message.trim().length;
				if (l === 0) {
					this.$notify({
						title: '',
						message: '不能发送空白消息',
						type: 'info',
						duration: 800
					})
					return;
				}
				this.activeItem.msglength = l;
				this.handledMessage()
				this.$store.commit("setOnSend", this.activeItem)
			}),
			//滚到底部
			handlerScrollDown(refName) {
				try {
					this.$nextTick(() => {
						this.$refs[refName].scrollTop = this.$refs[refName].scrollHeight;
					})
				} catch (error) {
					console.log("error", error.message);
				}
			},
			// 处理内容框的消息提示按钮
			handlerShowTip() {
				this.isShowNewMsgTip = false;
				this.isShowNewmobileTip = false;
				this.handlerScrollDown("scrollBoxRef");
			},
			//监听滚动条是否在底部 有信息的情况下 滚动条在底部 就把提示隐藏
			handleWatchScroll() {
				let _this = this;
				clearTimeout(_this.item);
				let num = this.$refs["scrollBoxRef"].scrollHeight - this.$refs["scrollBoxRef"].scrollTop - this.$refs[
					"scrollBoxRef"].clientHeight;
				if (num < 75) {
					this.isShowNewMsgTip = false;
					this.isShowNewmobileTip = false;
					return;
				}

				_this.item = setTimeout(() => {
					let newDifference = this.$refs["scrollBoxRef"].scrollHeight - this.$refs[
							"scrollBoxRef"]
						.scrollTop;
					if (_this.difference - newDifference > 75) {
						_this.isShowNewmobileTip = true;
						clearTimeout(_this.item)
					} else {
						_this.isShowNewmobileTip = false;
					}
					_this.difference = newDifference
				}, 700)


			},
			handledFormatDateHMS(date) {
				return formatTime(date, '{y}-{m}-{d}')
			},
			//判断日期是否相同 index 截取的字数
			formatDate(endd, index = 20) {
				if (!endd) {
					return "";
				}
				return DateIfSimilar(Date(), endd) ? formatDateHMS(endd).substring(0, index) : endd
					.substring(0,
						index);
			},

			//时间排序
			handleDateSort() {
				try {
					this.relationshipList.sort((a, b) => {
						return new Date(b.lastTime) - new Date(a.lastTime)
					})
				} catch (e) {
					console.log("时间排序处理错误", err)
				}
			},
			//更新红点和信息加时间
			handleTimeMsgUp(activeID, msg, isGroup, isNeedRedTip = false) {
				try {
					this.relationshipList.forEach((value, index, arr) => {
						if (value.otherId === activeID && value.isGroup === isGroup) {
							value.isNewMsgTipRed = isNeedRedTip;
							value.lastTime = this.formatDate(Date(), 10);
							let slh = ""
							if (msg.length >= 18) {
								slh = "..."
							}
							value.lastMessage = msg.substring(0, 18) + slh;
							throw new Error("Stop Iterating")
						}
					})
				} catch (error) {
					if (error.message !== 'Stop Iterating') console.log(error.message);
				}
			},
			handleChandeMsg() {
				this.pageConfig.pageNum += 1
				this.msgConfig.msglistResults = false
				this.handleGetMessageList(this.activeItem.activeId, true)
			},

		},

		watch: {
			//是否可以执行
			"isExecute": {
				deep: true,
				immediate: true,
				handler: function(value, oldvalue) {
					if (!value) return
					this.activeItem = {
						...this.activeItem,
						...this.storeUserinfo
					}
					this.userDialogIsShow=false;
					this.GroupDialogIsShow=false;
					// this.handleGetMessageList(this.activeItem.activeId)
				}
			},
			"storeUserinfo": {
				deep: true,
				immediate: true,
				handler: function(value, oldvalue) {
					if (!this.$store.getters.isExecute) return
					let oid = this.activeItem.fromId;
					this.activeItem.fromId = value.Id;
					this.activeItem.fromName = value.username;
					this.activeItem.fromUrl = value.url;
					if (oid != value.Id) {
						// this.handlerGetRelatinshipList(this.activeItem.fromId);
						this.initInfomation();
					}
					// //获取信息列表 获取公共群聊的信息 isFirstLoad:true,首次加载不执行
					// if (this.isFirstLoad) {
					// 	this.isFirstLoad = false;
					// } else {
					// 	this.handleGetMessageList(this.activeItem.activeId)
					// }
				}
			},
			"VisibleEmojiElement": {
				deep: true,
				immediate: true,
				handler: function(value, oldvalue) {
					if (value) {
						//监听
						document.addEventListener('click', this.handledVisibleEmojiElement);
					} else {
						//移除
						document.removeEventListener('click', this.handledVisibleEmojiElement);
					}
				}
			},

			"isGetRelationshiplist": {
				deep: true,
				handler: function(newVal, old) {
					if (newVal) {
						this.handlerGetRelatinshipList(this.activeItem.fromId);
						this.$store.commit("setIsGetRelationshiplist", false)
					}
				}
			},
			"newMessage": {
				deep: true, // 深度监听
				immediate: false, // 页面初始化时是否触发回调
				handler: function(newVal, oldVal) { // 监听属性的回调方法
					//判断消息类型
					let type = newVal.type;
					if (!this.$store.getters.isExecute) return
					if (type === 1) {
						//处于移动端时 不处理
						let myId = this.activeItem.fromId; //我是谁 用户ID
						let myActiveId = this.activeItem.activeId; //我的发送目标ID是谁
						let myActiveIsGroup = this.activeItem.isGroup; //我的发送目标是否是群聊
						let fromId = newVal.data.fromId; //发送方 用户ID
						let toActiveId = newVal.data.activeId; //发送方的发送目标 群ID或用户ID
						let isGroup = newVal.data.isGroup; //发送方的发送目标 是否是群聊

						/*新消息 */
						let num = this.$refs["scrollBoxRef"].scrollHeight - this.$refs["scrollBoxRef"].scrollTop - this
							.$refs["scrollBoxRef"].clientHeight;

						let newMsg = `[${newVal.data.fromName || newVal.data.userName}]向你发来了信息`
						if (isGroup) {
							newMsg = `群[${newVal.data.otherName}]有新消息啦`;
						}

						let isTrue = false; //true 滚到底部
						if (myId == fromId && myActiveId == toActiveId && myActiveIsGroup == isGroup) {
							//自己多端发送在同一个页面 包括自己
							isTrue = num < 75;
							num >= 75 ? this.isShowNewMsgTip = true : ""
							this.handledChangeMessageList(newVal.data)
							// 设置数据同步
							this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
						} else if (myId == fromId) {
							this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
						} else if (myId == toActiveId && isGroup == 0) {
							//别人 私发
							//在该页面
							if (myActiveId !== fromId) {
								this.$notify({
									title: '新消息',
									message: newMsg,
									type: 'success',
									duration: 2750
								});
								this.handleTimeMsgUp(fromId, newVal.data.message, isGroup, true);
							} else {
								isTrue = num < 75;
								num >= 75 ? this.isShowNewMsgTip = true : ""
								this.handledChangeMessageList(newVal.data)
								// 设置数据同步
								this.handleTimeMsgUp(fromId, newVal.data.message, isGroup);
							}
						} else if (myActiveIsGroup == 1 && isGroup == 1) {
							//别人群发
							//在该页面
							if (myActiveId == toActiveId) {
								isTrue = num < 75;
								num >= 75 ? this.isShowNewMsgTip = true : ""
								this.handledChangeMessageList(newVal.data)
								// 设置数据同步
								this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
							} else {
								//不在该页面
								this.$notify({
									title: '新消息',
									message: newMsg,
									type: 'success',
									duration: 750
								});
								this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup, true);
							}

						}

						if (isTrue) {
							this.handlerScrollDown("scrollBoxRef");
						}


					} else if (type === 4) {
						let myId = this.activeItem.fromId; //我是谁 用户ID
						let fromId = newVal.fromId;
						if (myId != fromId) {
							//好友同意请求
							this.$notify({
								title: '系统消息',
								message: `${newVal.fromUsername}成为你的好友了!`,
								type: 'success',
								duration: 750
							});
						}
						// 重新请求联系人
						this.handlerGetRelatinshipList(this.activeItem.fromId);
					} else if (type === 7) {
						//信息发送状态
						if (newVal.status) {
							this.activeItem.message = "";
							this.handlerScrollDown("scrollBoxRef");
						}
					} else if (type === 9) {
						this.handlerGetRelatinshipList(this.activeItem.fromId);
					} else if (type === 99) {
						try {
							//群聊
							if (newVal.code == "exit") {
								if (this.activeItem.fromId == newVal.exitUserId) {
									if (this.activeItem.activeId == newVal.groupId) {
										this.GroupDialogIsShow = false
										this.handleGroupSet(1, 1)
									}
									this.relationshipList = this.relationshipList.filter(item => {
										return !(item.isGroup == 1 && item.otherId == newVal.groupId);
									})
								} else {
									//其他用户 修改群的用户列表数据
									for (let i = 0; i < this.relationshipList.length; i++) {
										if (this.relationshipList[i].otherId == newVal.groupId && this
											.relationshipList[i].isGroup == 1) {
											this.$set(this.relationshipList[i], 'userlist', newVal.userlist)
											this.relationshipListTemp.userlist = newVal.userlist
											this.handledGetGroupUserList(this.relationshipListTemp.userlist)
											break;
										}
									}
								}
							} else if (newVal.code == "deletecontact") {
								//联系人 自己 //deleter删除者  deletedContact被删除者 
								this.userDialogIsShow = false;
								if (this.activeItem.fromId == newVal.deleter) {
									this.relationshipList = this.relationshipList.filter(item => {
										return !(item.isGroup == 0 && item.otherId == newVal.deletedContact);
									})
								} else {
									this.relationshipList = this.relationshipList.filter(item => {
										return !(item.isGroup == 0 && item.otherId == newVal.deleter);
									})
								}
								this.handleGroupSet(1, 1)
							} else if (newVal.code == "updateGroup") {
								for (let i = 0; i < this.relationshipList.length; i++) {
									if (this.relationshipList[i].otherId == newVal.Id && this.relationshipList[i]
										.isGroup == 1) {
										if (newVal.flag == 'updateGroupName') {
											this.$set(this.relationshipList[i], 'otherName', newVal.otherName)
											if (this.activeItem.activeId == newVal.Id && this.activeItem.isGroup ==
												1) {
												this.$set(this.relationshipListTemp, 'otherName', newVal.otherName)
												this.activeItem.otherName = newVal.otherName
											}
										} else if (newVal.flag == 'updateGroupUrl') {
											this.$set(this.relationshipList[i], 'otherUrl', newVal.otherUrl)
											if (this.activeItem.activeId == newVal.Id && this.activeItem.isGroup ==
												1) {
												this.$set(this.relationshipListTemp, 'otherUrl', newVal.otherUrl)
												this.activeItem.otherUrl = newVal.otherUrl
											}
										}
										break;
									}
								}


							}
						} catch (error) {
							console.log(error);
						}
					}

				},

			},


		}

	}
</script>

<style>
	.imageCls {
		width: 45px;
		height: 45px;
	}



	.pageMiddle {
		width: 800px;
		min-height: 641px;
		border: 1px solid #ccc;
		border-radius: 8px;
		box-shadow: -1px 1px 5px #ccc;
		box-sizing: border-box;
	}

	.main-title {
		height: 25px;
		line-height: 25px;
	}

	.mainBox {
		width: 100%;
		height: calc(100vh - 75px);
		min-height: 616px;
		display: flex;
		justify-content: space-around;
		padding-bottom: 10px;
	}

	.relationship {
		min-height: 614px;
		max-height: calc(100vh - 100px);
		overflow-y: auto;
		overflow-x: hidden;
		width: 250px;
		min-width: 250px;
		box-sizing: border-box;
		border-right: 1px solid #ccc;
	}


	.relationshipItem {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		text-align: left;
		cursor: pointer;
		padding: 5px 3px;
	}

	.relationshipItemND {
		display: flex;
		justify-content: flex-start;
	}

	.relationshipItemlasetDate {
		font-size: 12px;
		line-height: 18px;
	}

	.relationshipItemName {
		width: 113px;
		min-width: 113px;
		font-size: 18px;
		background: linear-gradient(90deg, #aaffff, #aaff7f, #aaff00);
		background-size: 0 3px;
		background-repeat: no-repeat;
		background-position: 0 100%;
		transition: 1s all;
		color: #000000;
	}

	.relationshipItem:hover .relationshipItemName {
		background-size: 100% 3px;
		color: #55ffff;
	}

	.relationshipItemMsg {
		width: 180px;
		min-width: 180px;
		font-size: 12px;
	}


	.content {
		height: calc(100vh - 95px);
		min-height: 616px;
		width: 100%;
		text-align: left;
		position: relative;
	}

	.contentTitle {
		width: 365px;
		max-width: 365px;
		min-width: 365px;
		margin: 8px 12px;
		font-size: 16px;
	}

	.contentMiddle {
		width: 100%;
		height: calc(100vh - 300px);
		min-height: calc(641px - 205px);
		overflow-y: auto;
		position: relative;
		border-top: 1px solid #ccc;
		border-bottom: 1px solid #ccc;
	}

	.contentDown {
		width: 100%;
		height: 105px;
		background-color: #fff;
	}

	.contentDownSend {
		position: absolute;
		right: 10px;
	}

	.isActive {
		background-color: #00A9FF;
	}



	/* 聊天界面 */
	.contentBox {
		margin: 10px;
	}

	.contentBoxLeft {
		display: flex;
		justify-content: flex-start;
		margin-top: 22px;
		position: relative;
	}

	.contentBoxRight {
		display: flex;
		justify-content: flex-start;
		flex-direction: row-reverse;
		margin-top: 22px;
		position: relative;
	}

	.fromMessage {
		margin: 18px 5px 0 5px;
		max-width: 448px;
		box-sizing: border-box;
		white-space: pre-wrap;
		overflow-wrap: anywhere;
		padding: 6px 3px;
		background-color: #CDF5FD;
		border-radius: 6px;
		text-align: left;
		display: block;
	}

	.contentName {
		position: absolute;
		left: 45px;
		font-size: 14px;
		color: #cacaca;
	}

	.contentNameRight {
		right: 45px;
		position: absolute;
		font-size: 14px;
		color: #cacaca;
	}

	.contentMessageDateBox {
		position: absolute;
		top: -18px;
		width: 100%;
	}

	.contentMessageDate {
		text-align: center;
		margin: 0 auto;
		width: 160px;
		color: #ccc;
		font-size: 14px;
	}

	/* 消息提示 */


	.MsgTipBox {
		position: relative;
	}

	.MsgTip {
		position: absolute;
		cursor: pointer;
		text-align: center;
		height: 35px;
		line-height: 35px;
		padding: 0 12px 0 12px;
		right: 0px;
		top: -75px;
		border-radius: 12px 0 0 12px;
		background-color: #aaffff;
	}

	.MsgTip:hover {
		background-color: #a2f3f3;
	}

	.MsgTip:active {
		background-color: #94dede;
	}

	.MsgTip span {
		margin-left: 3px;
		font-size: 14px;
	}

	.icon-shuangxiangxiajiantou:before {
		animation-name: example;
		animation-duration: .6s;
		animation-iteration-count: infinite;
		animation-direction: alternate-reverse;
		color: #e6e6e6;
	}

	/* 动画代码 */
	@keyframes example {
		0% {
			color: #e6e6e6;
		}

		100% {
			color: #00aaff;
		}
	}


	/* 消息红点 */
	.TipREDBox {
		position: relative;
	}

	.TipRED {
		position: absolute;
		width: 10px;
		height: 10px;
		border-radius: 50%;
		right: 0;
		top: -3px;
		background-color: #f00;
	}

	.hintContentButtom {
		width: 100%;
		height: 30px;
		position: absolute;

	}

	.hintContentButtom .updateImage {
		position: relative;
		text-align: center;
	}

	.hintContentLength {
		display: inline-block;
		position: absolute;
		right: 80px;
		height: 27px;
		line-height: 27px;
		color: #ccc;
		font-size: 12px;
	}

	.hintContentNowLength {
		display: inline-block;
		font-size: 14px;
	}

	.msgImagesCls {
		width: 300px;
		height: 250px;
	}

	.ControlsBoxDialog .el-dialog {
		width: 45%;
		min-width: 350px;
		height: auto;
		background-image: linear-gradient(to top, #bdc2e8 0%, #d0d9e8 1%, #f2eaf5 100%);
		border-radius: 8px;
	}

	.GroupDialogFormUserListBox {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		box-sizing: border-box;
		width: 85%;
		max-height: 200px;
		overflow: hidden;
		overflow-y: auto;
		flex-wrap: wrap;
		-ms-flex-wrap: wrap;

	}

	.GroupDialogFormUserListBox .item {
		padding: 3px;
		text-align: center;
	}
</style>